// components/verifyLogin/verifyLogin.js
let request = require('../../utils/request.js')

Component({
  options: {
    addGlobalClass: true
  },
  /**
   * 组件的属性列表
   */
  properties: {
    verifyLoginDialog: {
      type: Boolean,
      value: false
    }
  },

  /**
   * 组件的初始数据
   */
  data: {
    userInfo: {}
  },

  /**
   * 组件的方法列表
   */
  methods: {
    /**
   * 授权登录
   */
    bindGetUserInfo: function (e) {
      let that = this;
      let userInfo = e.detail.userInfo;
      wx.setStorageSync('lmtc_userInfo', userInfo)
      if (userInfo) {
        this.setData({
          userInfo: userInfo
        })
        wx.login({
          success: res => {
            that.getToken(res.code);
          }
        });
      }
    },
    /**
     * 获取Token
     * @param {String} code 微信返回的用户code
     */
    getToken(code, src) {
      let that = this
      let info = this.data.userInfo;
      let url = '/customer/info/authorize'
      let params = {
        avatar: info.avatarUrl,
        code: code,
        nickname: info.nickName,
        sex: info.gender == 0 ? 'UNKNOWN' : info.gender == 1 ? 'MEN' : 'WOMEN',
      }
      request.http(url, 'POST', params)
        .then(res => {
          var data = res.data
          if (data.code == 200) {
            let token = data.data.token
            wx.setStorageSync('lmtc_token', token)
            wx.setStorageSync('lmtc_customerId', data.data.customerId)
            that.triggerEvent('verifyLogin')
            that.setData({
              verifyLoginDialog: false
            })
          } else {
            wx.removeStorageSync('lmtc_userInfo')
          }
        })
    },
    hiddenVerifyLoginDialog() {
      this.setData({
        verifyLoginDialog: false
      })
    }
  }
})
